const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { getPassword } = require('../utils/crypto')
const { exec } = require('../db/index')

// 登陆接口
router.post('/api/login', async (ctx, next) => {
	// 1. 接收参数
	const { username, password } = ctx.request.body
	// 2. 基于参数处理 数据
	// 2.1. 查询用户是否存在，如果不存在，让用户注册
	const queryInfo = await exec(`select * from users where username=?`, [
		username
	])
	if (queryInfo.length !== 0) {
		// 2.2 登陆
		const data = await exec(
			`select * from users where username=? and password=?`,
			[username, getPassword(password)]
		)
		console.log('data:', data)
		// 2.3 token
		const token = jwt.sign(
			{ id: data[0].id, username: data[0].username },
			'1904',
			{ expiresIn: '24h' }
		)
		ctx.body = { code: 0, msg: 'success', data: { token } }
	} else {
		ctx.body = { code: 0, msg: '请注册' }
	}
})

// 注册接口
router.post('/api/register', async (ctx, next) => {
	// 1. 接收参数
	const { username, password, avatar, nickname = '' } = ctx.request.body
	// 2. 处理根据exec
	const insertData = await exec(
		`insert into users (username, password,avatar,nickname) values (?,?,?,?)`,
		[username, getPassword(password), avatar, nickname]
	)
	if (insertData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: '注册成功',
			data: { insertId: insertData.insertId }
		}
	} else {
		ctx.body = {
			code: -1,
			msg: '注册失败'
		}
	}
	// 3. 返回思路
})

// 查询用户接口 分页
router.get('/api/users', async (ctx, next) => {
	console.log('----------------------ctx.path')
	// 接收权限id
	const { id } = ctx.state.userInfo
	// 1. 接收参数
	console.log('id,', id)
	const { page = 1, size = 5 } = ctx.query
	// 2. 处理参数 排序 order by id desc 倒序
	const list = await exec(`select * from users where id=? limit ? offset ?`, [
		id,
		size * 1,
		(page - 1) * size
	])
	console.log('list', list)
	ctx.body = {
		code: 0,
		msg: '查询成功',
		data: { list }
	}
	// // 3. 返回数据
	// if (list.length !== 0) {
	// 	ctx.body = {
	// 		code: 0,
	// 		msg: '查询成功',
	// 		data: { list }
	// 	}
	// } else {
	// 	ctx.body = {
	// 		code: -1,
	// 		msg: '查询失败'
	// 	}
	// }
})

module.exports = router
